<?php
class ControllerNewsletterNewsletter extends Controller {
    private $error = array();

    public function index() {
        $this->load->language('newsletter/subscriber'); 
        $this->document->title = $this->language->get('heading_title'); 

        $this->data['heading_title'] = $this->language->get('heading_title');
        $this->data['form_title'] = 'Send newsletter';
        $this->data['text_send'] = $this->language->get('text_send');
        $this->data['text_cancel'] = $this->language->get('text_cancel');
        $this->data['text_email'] = $this->language->get('text_email');
        $this->data['text_date'] = $this->language->get('text_date');           
        $this->data['text_from'] = $this->language->get('text_from');
        $this->data['text_to'] = $this->language->get('text_to');
        $this->data['text_continue'] = $this->language->get('text_continue');
        $this->data['text_subject'] = $this->language->get('text_subject');
        $this->data['text_message'] = $this->language->get('text_message');
        $this->data['text_sent'] =  $this->language->get('text_sent');
        
        $this->data['token'] = $this->session->data['token'];  
        $this->data['item_send'] = isset($this->data['item_send']) ? $this->data['item_send'] : false;      
        
        $this->data['action'] = HTTPS_SERVER . 'index.php?route=newsletter/newsletter&token=' . $this->session->data['token'];
        $this->data['cancel'] = HTTPS_SERVER . 'index.php?route=newsletter/subscriber&token=' . $this->session->data['token'];
        $this->data['continue'] = HTTPS_SERVER . 'index.php?route=newsletter/newsletter&token=' . $this->session->data['token'];
        $this->data['preview'] = HTTPS_SERVER . 'index.php?route=newsletter/newsletter/preview&token=' . $this->session->data['token'];
        
        $this->data['from_name']  = isset($this->request->post['from_name']) ? $this->request->post['from_name'] : $this->config->get('config_owner'); 
        $this->data['from_email'] = isset($this->request->post['from_email']) ? $this->request->post['from_email'] : $this->config->get('config_email'); 
        $this->data['to']         = isset($this->request->post['to']) ? $this->request->post['to'] : '';
        $this->data['subject']    = isset($this->request->post['subject']) ? $this->request->post['subject'] : '';
        $this->data['template']    = isset($this->request->post['template']) ? $this->request->post['template'] : '0';
        if(isset($this->request->post['message'])){
            $message = $this->request->post['message'];    
            //$message = str_replace('\\"', '"', html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
        }
        else{
            $message = '';
        }
        $this->data['message'] = $message;
        $this->data['image_path'] = HTTPS_SERVER . 'index.php?route=common/filemanager&token=' . $this->session->data['token'];
        
        $this->load->model('newsletter/subscriber'); 
        $results = $this->model_newsletter_subscriber->getList(); 
        $this->data['subscribers'] = array();
        foreach($results as $row){
            $this->data['subscribers'][] = array(
                'email' => $row['email'],
                'date'  => date($this->language->get('date_format_short'), strtotime($row['date_added'])),
                'name'  => $row['name'],
            );    
        }        

        $this->load->model('newsletter/template'); 
        //$this->data['templates'] = $this->model_newsletter_template->getAllTemplates();
        $this->data['templates'] = $this->model_newsletter_template->getEnabledTemplates();
                
        if(($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()){
            /*
            $message  = '<html dir="ltr" lang="en">' . "\n";
            $message .= '<head>' . "\n";
            $message .= '<title>' . $this->request->post['subject'] . '</title>' . "\n";
            $message .= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' . "\n";
            $message .= '</head>' . "\n";
            //$message .= '<body>' . html_entity_decode($message, ENT_QUOTES, 'UTF-8') . '</body>' . "\n";        
            $message .= '<body>' . html_entity_decode($this->data['message'], ENT_QUOTES, 'UTF-8') . '</body>' . "\n";        
            $message .= '</html>' . "\n";
            
            $message .= html_entity_decode($this->data['message'], ENT_QUOTES, 'UTF-8') . "\n";   
            */ 
            //$template = new Template();
            //$message = $template->fetch('mail/newsletter_template.tpl'); 
              
            $message = $this->loadTemplate($this->request->post['template']);
            
            $attachments = array();            
            if(preg_match_all('#(src="([^"]*)")#mis', $message, $matches)){              
                foreach ($matches[2] as $key => $value) {
                    $filename = md5($value) . strrchr($value, '.');
                    $path = rtrim($this->request->server['DOCUMENT_ROOT'], '/') . parse_url($value, PHP_URL_PATH);
                            
                    $attachments[] = array(
                        'filename' => $filename,
                        'path'     => $path
                    );
                            
                    $message = str_replace($value, 'cid:' . basename($filename), $message);
                }              
            } 
             
            $emails = $this->request->post['to']; 
            /*
            foreach ($emails as $email){
                $this->sendMail($email, $attachments, $message);    
            } 
            */
            $this->sendMailMwcMailer($emails, $attachments, $message);    
            
            $this->session->data['success'] = $this->language->get('text_sendmail_success'); 
            $this->data['item_send'] = true; 
            
            //$this->redirect($this->data['action']);
            //return; 
        }
        elseif($this->error){
            reset($this->error);
            $this->data['error'] = current($this->error);
        } 
        else{
            unset($this->data['error']);
        }
        
        $this->template = 'newsletter/newsletter.tpl';
        $this->children = array(
            'common/header',    
            'common/footer'    
        );
        
        $this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
    }
      
    private function sendMailMwcMailer($emails, $attachments, $message){        
        require_once(DIR_MAILER . 'mwc_mailer.php');
        
        $mail = new MwcMailer(); 
        if($this->config->get('config_mail_protocol') == 'smtp'){           
            $mail->Host = $this->config->get('config_smtp_host');
            $mail->Username = $this->config->get('config_smtp_username');
            $mail->Password = $this->config->get('config_smtp_password');
            $mail->Port = $this->config->get('config_smtp_port');            
        
            $mail->IsSMTP();
        }
                
        $mail->setFrom($this->request->post['from_email'], $this->request->post['from_name']);                     
        $mail->Subject = $this->request->post['subject'];
        $mail->MsgHTML($message);
        
        foreach ($emails as $email) {
            $mail->AddBCC($email);
        }
        
        foreach ($attachments as $attachment) {
            if(file_exists($attachment['path'])){
                $mail->addAttachment($attachment['path'], $attachment['filename']);
            }            
        }
        
        $mail->send();            
    }
    
    public function preview(){
        $template_id = $this->request->get['template_id'];
        
        $output = $this->loadTemplate($template_id);
        
        $this->response->setOutput($output, $this->config->get('config_compression'));           
    }
    
    private function sendMail($email, $attachments, $message){          
        $mail = new Mail();    
        $mail->protocol = $this->config->get('config_mail_protocol');
        $mail->parameter = $this->config->get('config_mail_parameter');
        $mail->hostname = $this->config->get('config_smtp_host');
        $mail->username = $this->config->get('config_smtp_username');
        $mail->password = $this->config->get('config_smtp_password');
        $mail->port = $this->config->get('config_smtp_port');
        $mail->timeout = $this->config->get('config_smtp_timeout');
                    
        $mail->setFrom($this->request->post['from_email']);             
        $mail->setTo($email);        
        $mail->setSender($this->request->post['from_name']);        
        $mail->setSubject($this->request->post['subject']);
        foreach ($attachments as $attachment) {
            if(file_exists($attachment['path'])){
                $mail->addAttachment($attachment['path'], $attachment['filename']);
            }            
        }
        $mail->setHtml($message);
        $mail->send();   
    }
    
    private function validate(){
        $pattern = '/^[A-Z0-9._%-+]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z]{2,6}$/i';         
        
        if(!isset($this->request->post['from_email'])){
            $this->error['from'] = $this->language->get('error_email_from');
        }
        
        if(!isset($this->request->post['to']) || empty($this->request->post['to'])){
            $this->error['to'] = $this->language->get('error_email_to');
        }
        
        if(!isset($this->request->post['subject']) || strlen(utf8_decode($this->request->post['subject'])) < 1){
            $this->error['subject'] = $this->language->get('error_subject');
        }
        
        if(!isset($this->request->post['template']) || $this->request->post['template'] == 0){
            $this->error['template'] = $this->language->get('error_template');
        }
        
        /*
        if(!isset($this->request->post['message'])) {
            $this->error['message'] = $this->language->get('error_message');
        }
        */
         
        if (!$this->user->hasPermission('modify', 'newsletter/newsletter')) {
            $this->error['warning'] = $this->language->get('error_permission');
        }
                           
        if(!$this->error){
            return TRUE;
        } 
        else{
            return FALSE;
        }
    } 
    
    private function loadTemplate($template_id){
        $this->load->language('newsletter/subscriber'); 
        $this->load->model('newsletter/template');
        $this->load->model('tool/image');
        $this->load->model('tool/seo_url');
        $this->load->model('catalog/manufacturer');
        
        $this->document->title = $this->language->get('heading_title'); 
        $this->data['heading_title'] = $this->language->get('heading_title');
        
        $template = $this->model_newsletter_template->getTemplate($template_id);
        
        $this->data['title'] = html_entity_decode($template['title']);
        $this->data['description'] = html_entity_decode($template['description']);        
        $this->data['product_title'] = html_entity_decode($template['product_title']);
        $this->data['footer_text'] = html_entity_decode($template['footer_text']);
        
        $currency = new Currency($this->registry);        
        
        $products = $this->model_newsletter_template->getProducts($template_id);
        $this->data['products'] = array();
        foreach($products as $product){
            if($product['image'] && file_exists(DIR_IMAGE . $product['image'])) {
                $image_file = $product['image'];    
            } 
            else {
                $image_file = 'no_image.jpg';
            }
            $path = $this->model_newsletter_template->getCategoriesPath($product['product_id']);
            $link = HTTP_SERVER . 'index.php?route=product/product&path=' . $path . '&product_id=' . $product['product_id'];
            
            $price = $product['price']; 
            $price_formatted = $currency->formatPrice($price); 
            $discount = 0;
            $discount_formatted = 0;
            if((int)$product['discount'] > 0){
                $discount = $product['discount'];                 
                $discount_formatted = $currency->formatPrice($discount);    
            }
            else{
                $discount_data = $this->model_newsletter_template->getDiscount($product['product_id']); 
                if($discount_data > 0){
                    $discount = $discount_data;
                    $discount_formatted = $currency->formatPrice($discount); 
                }
                   
                $discounts_data = $this->model_newsletter_template->getProductDiscounts($product['product_id']);             
                if($discounts_data){   
                    $discount = $discounts_data[0]['price'];                 
                    $discount_formatted = $currency->formatPrice($discount);
                }
            }
            
            $percent = round((($price - $discount) / $price) * 100);
            $this->data['products'][] = array(
                'name'      => html_entity_decode($product['name']),
                'link'      => $this->model_tool_seo_url->rewrite($link),
                //'image'     => $this->model_tool_image->resize($image_file, 140, 170),
                'image'     => $this->model_tool_image->resize($image_file, 136, 153),
                'price'     => $price_formatted,
                'discount'  => $discount_formatted,
                'percent'   => $percent,
            );    
        }
        
        $manufacturers = $this->model_catalog_manufacturer->getManufacturers();
        foreach($manufacturers as &$manufacturer){
            $link = HTTP_SERVER . 'index.php?route=product/manufacturer/viewManufacturer&manufacturer_id=' . $manufacturer['manufacturer_id']; 
            
            $manufacturer['href'] = $this->model_tool_seo_url->rewrite($link);
        }
        $this->data['manufacturers'] = $manufacturers;
        
        $this->template = 'mail/newsletter_template.tpl';
        
        return $this->render(true);
    }   
}
?>